﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using DevExpress.Xpf.Grid;
using DAL.BAL;
using DAL.Models;
using System.Data.Objects.DataClasses;

namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for Candidates.xaml
    /// </summary>
    public partial class Candidates : Window
    {
        private int candidateTypeId = int.MinValue;
                
        public Candidates()
        {
            InitializeComponent();

            foreach (Window w in Application.Current.Windows)
            {
                if (w is MainWindow)
                    if ((w as MainWindow).DataTransition != null)
                        this.candidateTypeId = (int)(w as MainWindow).DataTransition;
            }

            gridControl1.View.AllowEditing = false;
             
            if (!Business.CanEditCandidates())
            {
                deleteRowItem.IsVisible = false;

                bDelete.IsVisible = false;

                bNew.IsVisible = false;

            }

            if (Business.CanInsertCandidatesAsContactPersons())
                bNew.IsVisible = true;

            if (!Business.CanFindCandidate())
            {
                FindVacancies.IsVisible = false;
            }

            //if (!Business.CanEditCandidates())
            //{
            //    columnPhone.Visible = false;
            //}

            if (Business.currentUser.RoleID != 1)
            {
                SyncAdd.IsVisible = false;

                SyncDelete.IsVisible = false;
            }

             
            Refresh();

        }

        private void Refresh()
        {
            try
            {  
                //Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, Business.MyEntities.Candidates);

                //Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, Business.MyEntities.Candidate_VacancyHistory);

                if (this.candidateTypeId != int.MinValue)
                    gridControl1.ItemsSource = from n in Business.GetCandidates()
                                               where n.Candidate_Types.Id == this.candidateTypeId
                                               select n;
                else
                    gridControl1.ItemsSource = Business.GetCandidates();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void deleteRowItem1_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                DAL.Models.Candidate ec = (DAL.Models.Candidate)gridControl1.GetRow(gridControl1.View.FocusedRowHandle);


                if (ec != null)
                {
                    for (int i = ec.Candidat_RangeTerritories.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_RangeTerritories.ToList()[i]);
                    }

                    for (int i = ec.Candidate_Positions.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidate_Positions.ToList()[i]);
                    }
                
                    for (int i = ec.Candidat_VacancyHistory .Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_VacancyHistory.ToList()[i]);
                    }

                    for (int i = ec.Candidat_Expiriences.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_Expiriences.ToList()[i]);
                    }

                    for (int i = ec.Candidat_ExceptCommodityGroups .Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_ExceptCommodityGroups.ToList()[i]);
                    }
                    
                    for (int i = ec.Candidat_EMails.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_EMails.ToList()[i]);
                    }

                    for (int i = ec.Candidat_Phones.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_Phones.ToList()[i]);
                    }

                    for (int i = ec.Candidat_ExceptEmployers.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_ExceptEmployers.ToList()[i]);
                    }

                    for (int i = ec.Employer_ContactPersons.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Employer_ContactPersons.ToList()[i]);
                    }

                    for (int i = ec.Candidate_Resume.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidate_Resume.ToList()[i]);
                    }

                    for (int i = ec.SentEmailsHistories.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.SentEmailsHistories.ToList()[i]);
                    }

                    foreach (Vacancy v in ec.Vacancies)
                    {
                        v.Candidate1 = null;
                    }

                    foreach (Vacancy v in ec.Vacancies1)
                    {
                        v.Candidate = null;
                    }
                }

                Business.DeleteObject(ec);

                gridControl1.View.CommitEditing();

                (gridControl1.View as GridViewBase).DeleteRow(gridControl1.View.FocusedRowHandle);



                try
                {
                    Business.Save();

                    gridControl1.RefreshData();
                }
                catch (Exception e1)
                {
                    if (e1.InnerException.Message.Contains(WpfClient.Properties.Resources.DeleteReferenceMessage))
                        MessageBox.Show(WpfClient.Properties.Resources.DeleteWarning, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK
                            , MessageBoxImage.Warning);
                    else
                        MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);

                    Business.Cancel();

                    Refresh();
                }
            }
        }

        private void RefreshItem_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Refresh();
        }

        private void bNew_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            try
            {
                Candidate candidate = new Candidate();

                CandidateEdit candidateEdit = new CandidateEdit(candidate, true, Business.CanEditCandidates() || Business.CanInsertCandidatesAsContactPersons());

                if (candidateEdit.ShowDialog() == true)
                {
                    Business.Save();

                    Refresh();
                }
                else
                    Business.Cancel();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void gridControl1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                Candidate candidate = Business.GetCandidateById(((Candidate)gridControl1.GetFocusedRow()).Id);
                                
                if (candidate != null)
                {
                    CandidateEdit candidateEdit = new CandidateEdit(candidate, false, Business.CanEditCandidates());

                    if (candidateEdit.ShowDialog() == false)
                    {
                        Business.Cancel();

                        Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, candidate);
                    }
                    else
                    {
                        Business.Save();


                        if (candidateTypeId != int.MinValue)
                        {
                            if (candidate.Candidate_Types.Id != candidateTypeId)
                            {
                                Refresh();
                            }
                            else
                            {
                                Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, candidate);

                                gridControl1.RefreshRow(gridControl1.View.FocusedRowHandle);
                            }
                        }
                        else
                        {
                            Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, candidate);

                            gridControl1.RefreshRow(gridControl1.View.FocusedRowHandle);
                        }

                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void FindVacancies_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
             Candidate candidate = (Candidate)gridControl1.GetFocusedRow();

            if (candidate != null)
            {
                Find_Vacancies find_Vacancies = new Find_Vacancies(candidate);

                find_Vacancies.ShowDialog();
            }
        }

        private void gridControl1_CustomUnboundColumnData(object sender, GridColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Phones")
            {
                if (e.IsGetData)
                {
                    EntityCollection<Candidat_Phones> phonesCollection = (EntityCollection<Candidat_Phones>)e.GetListSourceFieldValue("Candidat_Phones");

                    List<Candidat_Phones> data = phonesCollection.Select(c => c).ToList();
                    
                    string _phones = string.Empty;

                    foreach (Candidat_Phones cp in data)
                    {
                        _phones += string.Format("{0};", cp.Phone);
                    }

                    e.Value = _phones;
                }
            }
            else
                if (e.Column.FieldName == "Positions")
                {
                    int key = (int)e.GetListSourceFieldValue("Id");

                    if (e.IsGetData)
                    {
                        EntityCollection<Candidate_Positions> phonesCollection = (EntityCollection<Candidate_Positions>)e.GetListSourceFieldValue("Candidate_Positions");

                        List<Candidate_Positions> data = phonesCollection.Select(c => c).ToList();

                        string _positions = string.Empty;
                          
                        foreach (Candidate_Positions cp in data)
                        {
                            if (cp.Position != null)
                                _positions += string.Format("{0};", cp.Position.PositionName);
                        }

                        e.Value = _positions;
                    }
                }
                else
                    if (e.Column.FieldName == "RangeTerritory")
                    {
                        if (e.IsGetData)
                        {
                            EntityCollection<Candidat_RangeTerritories> phonesCollection = (EntityCollection<Candidat_RangeTerritories>)e.GetListSourceFieldValue("Candidat_RangeTerritories");

                            List<Candidat_RangeTerritories> data = phonesCollection.Select(c => c).ToList();

                            string _rangeTerritory = string.Empty;

                            foreach (Candidat_RangeTerritories cp in data)
                            {
                                _rangeTerritory += string.Format("{0};", cp.Territory.TerritoryName);
                            }

                            e.Value = _rangeTerritory;
                        }
                    }
                    else
                    {
                        if (e.IsGetData)
                        {
                            EntityCollection<Candidat_VacancyHistory> vacancyHistoryCollection = (EntityCollection<Candidat_VacancyHistory>)e.GetListSourceFieldValue("Candidat_VacancyHistory");

                            List<Candidat_VacancyHistory> data = vacancyHistoryCollection.Select(c => c).ToList();

                            if (e.Column.FieldName == "ReportCVs")
                            {
                                e.Value = data.Count.ToString();
                            }
                            else
                            {
                                int res = 0;

                                foreach (Candidat_VacancyHistory cvh in data)
                                {
                                    if (e.Column.FieldName == "ReportInterviews")
                                    {
                                        if (cvh.InterviewDate != null)
                                            res++;
                                    }
                                    else
                                    {
                                        if (cvh.InterviewResult != null)
                                            res++;
                                    }
                                }

                                e.Value = res.ToString();
                            }
                        }
                    }
        }

        private void SyncAdd_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
             Candidate candidate = (Candidate)gridControl1.GetFocusedRow();

             if (candidate != null)
             {
                 string res = Classes.SyncCandidateWithWebSite.AddToWebSite(candidate);

                 if (res != string.Empty)
                     MessageBox.Show(res, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                 else
                     MessageBox.Show("Информация отправлена на сайт", WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);
             }
        }

        private void SyncDelete_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Candidate candidate = (Candidate)gridControl1.GetFocusedRow();

            if (candidate != null)
            {
                string res = Classes.SyncCandidateWithWebSite.DropFromWebSite(candidate);

                if (res != string.Empty)
                    MessageBox.Show(res, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    MessageBox.Show("Информация удалена с сайта", WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        
    }
}
